package com.yang.system.domain.orgMng.org;

import com.yang.system.domain.common.validator.CommonValidator;
import com.yang.system.domain.orgMng.org.validator.CancelOrgValidator;
import com.yang.system.domain.orgMng.org.validator.OrgLeaderValidator;
import com.yang.system.domain.orgMng.org.validator.OrgNameValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

// OrgHandler 来协助完成 修改组织信息和撤销组织功能
@Component
public class OrgHandler {
    private final CommonValidator commonValidator;
    private final OrgNameValidator nameValidator;
    private final OrgLeaderValidator leaderValidator;
    private CancelOrgValidator cancelValidator;

    @Autowired
    public OrgHandler(CommonValidator commonValidator,
                      OrgNameValidator nameValidator,
                      OrgLeaderValidator leaderValidator,
                      CancelOrgValidator cancelValidator){
        this.commonValidator = commonValidator;
        this.nameValidator = nameValidator;
        this.leaderValidator = leaderValidator;
        this.cancelValidator = cancelValidator;
    }

    public void updateBasic(Org org, String newName, Long newLeaderId, Long userId) {
        updateName(org, newName);
        updateLeader(org, newLeaderId);
        updateAuditInfo(org, userId);
    }

    public void cancel(Org org, Long userId) {
        cancelValidator.cancelledOrgShouldNotHasEmp(org.getTenantId(), org.getId());
        cancelValidator.OnlyEffectiveOrgCanBeCancelled(org);
        org.cancel();   // 只需告诉 Org 要进行撤销，但不必了解 Org 内部细节
        updateAuditInfo(org, userId);
    }

    private void updateLeader(Org org, Long newLeader) {
        if (newLeader != null && !newLeader.equals(org.getLeaderId())) {
            leaderValidator.leaderShouldBeEffective(org.getTenantId(), newLeader);
            org.setLeaderId(newLeader);
        }
    }
    private void updateName(Org org, String newName) {
        if (newName != null && !newName.equals(org.getName())) {
            nameValidator.orgNameShouldNotEmpty(newName);
            nameValidator.nameShouldNotDuplicatedInSameSuperior(org.getTenantId(), org.getSuperiorId(), newName);
            org.setName(newName);
        }
    }
    private void updateAuditInfo(Org org, Long userId) {
        // 设置最后修改人和时间
        org.setLastUpdatedBy(userId);
        org.setLastUpdatedAt(LocalDateTime.now());
    }
}
